package com.bytedance.video.common;

import com.bytedance.video.mapper.VideoMapper;
import com.bytedance.video.pojo.Video;
import com.bytedance.video.request.PublishVideoActionRequest;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

import java.io.*;
import java.util.Map;

@Data
@Slf4j
public class HandlerUploadFileThread extends Thread {
    private String fileName;
    private String uuid;
    private String lastName;
    private VideoMapper videoMapper;
    private PublishVideoActionRequest publishVideoActionRequest;
    private Long userid;
    private String localFilePath;

    @SneakyThrows
    @Override
    public void run() {
        String uploadVideoRealPath = QiniuUtil.UploadByFile(fileName, localFilePath);
        //截取视频的封面
        log.info("查看文件名:" + fileName);
        log.info("上传的http全路径:" + uploadVideoRealPath);
        //判断文件是不是视频，视频则截取封面，不是则同为封面
        String upImageUrl = null;
        if (".mp4".equals(lastName)) {
            //是MP4格式
            Map<String, Object> screenshot = UploadUtil.getScreenshot(localFilePath);
            //获取根路径，包含后缀
            String imagePath = (String) screenshot.get("4imagePath");
            String imageName = UploadCode.VIDEO_COVER + uuid + ".jpg";
            FileInputStream fileInputStream = new FileInputStream(imagePath);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            upImageUrl = QiniuUtil.UploadByInput(imageName, bufferedInputStream);
            bufferedInputStream.close();
            fileInputStream.close();
            //删除照片
            File file = new File(imagePath);
            file.delete();
        }
        //删除视频
        File file1 = new File(localFilePath);
        file1.delete();
        if (upImageUrl == null) {
            //为空说明是照片
            upImageUrl = uploadVideoRealPath;
        }
        //写入数据库
        Video video = new Video();
        video.setTitle(publishVideoActionRequest.getTitle());
        video.setCover_url(upImageUrl);
        video.setPlay_url(uploadVideoRealPath);
        video.setUser_id(userid);
        video.setCreate_time(System.currentTimeMillis());
        video.setFavorite_count(new Long(0));
        video.setComment_count(new Long(0));
        //将video的info写入数据库
        videoMapper.insertVideoInfo(video);
        //获取出生成的video_id
        Long videoId = video.getId();
        log.info("获取出生成的video_id:" + videoId.toString());
    }
}
